const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    location_detail: {},
    popup_show: false,
    showCalendar: false,
    calendarEvents: [],
    time_op: '',
    timeList:[],
    time_day:"",
    save_time: "", //保存原始时间
    showAddress: false,
    id: "",
    dataDetail: {},
    content: "",
    info: false,
    myLocation: {},
    activeNames: [1],
    imgPath: app.globalData.imgPath,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      id: options.id,
      myLocation: wx.getStorageSync("address-point"),
    })
    this.getAddress();
    this.getTimeGroup(new Date(this.data.time_day).getTime() / 1000);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  confirmSelectAddress(item) {
    this.setData({
      location_detail: item.detail,
      showAddress: false
    })
  },
  tapShowAddress() {
    this.setData({
      showAddress: true
    })
  },
  onChangeField(event) {
    this.setData({
      content: event.detail
    })
  },
  clickAppointment() {
    this.setData({
      save_time: this.data.time_op !== '' ? [this.data.time_day.split('-')[0],this.data.time_day.split('-')[1],this.data.time_day.split('-')[2],this.data.time_op] : '',
      time_day: new Date().getFullYear()+"-" + (new Date().getMonth()+1) + "-" + new Date().getDate(),
      time_op: "",
      popup_show: true
    })
    // this.getTimeGroup(new Date(this.data.time_day).getTime() / 1000);
  },
  selectedDay(e) {
    let format_time = `${e.detail.work_date.split('-')[0]}-${e.detail.work_date.split('-')[1]}-${e.detail.work_date.split('-')[2]}`;
    this.setData({
      time_day: format_time,
      time_op: ""
    })
    this.getTimeList(new Date(`${e.detail.work_date.split('-')[0]}-${this.filterDate(e.detail.work_date.split('-')[1])}-${e.detail.work_date.split('-')[2]}`).getTime() / 1000);
  },
  chooseTime(op) {
    if(op.currentTarget.dataset.item.state == 0) {
      this.setData({
        time_op: op.currentTarget.dataset.item.time_str
      })
    }
  },
  cancalTime() {
    if(this.data.save_time) {
      this.setData({
        time_day: this.data.save_time[0]+'-'+this.data.save_time[1]+'-'+this.data.save_time[2],
        time_op: this.data.save_time[3],
        popup_show: false,
      })
    }else {
      this.setData({
        popup_show: false,
        time_op: ""
      })
    }
  },
  sureTime() {
    this.setData({
      popup_show: false
    })
  },
  onChangeCollapse(event) {
    this.setData({
      activeNames: event.detail,
    });
  },
  // 获取地址
  getAddress() {
    let baseUrl = app.getNetAddresss("member.member-address.index");
    app._postNetWork({
      url: baseUrl,
      success: ({data : { data,result,msg }}) => {
        if (result !== 1) {
          app.tips(msg)
          return false;
        }
        if(data.length > 0) {
          for(let item of data) {
            if(item.isdefault == 1) {
              this.setData({
                location_detail: item
              })
            } 
          }
        }
        this.getData();
      }
    });
  },
  // 获取详情
  getData() {
    let baseUrl = app.getNetAddresss("plugin.be-within-call.frontend.create-need.pre-ability");
    app._postNetWork({
      url: baseUrl,
      data: {
        aid : this.data.id
      },
      success: ({data : { data,result,msg }}) => {
        if (result !== 1) {
          app.tips(msg)
          setTimeout(() => { 
            wx.navigateBack({ 
              delta: 1, 
            })
          },1000)
          return false;
        }
        this.setData({
          dataDetail: data
        })
      }
    });
  },
  // 选择预约指定时间
  getTimeList(date) {
    this.setData({
      timeList: []
    })
    wx.showLoading({
      title: "加载中",
      mask: true,
    });
    let baseUrl = app.getNetAddresss("plugin.be-within-call.frontend.work-time.pre-time");
    app._postNetWork({
      url: baseUrl,
      data: {
        aid : this.data.id ,
        date
      },
      success: ({data : { data,result,msg }}) => {
        wx.hideLoading();
        if (result !== 1) {
          app.tips(msg)
          return false;
        }
        this.setData({
          timeList: data.time_list
        })
      }
    });
  },
  // 技能工作时间分组
  getTimeGroup(date) {
    let baseUrl = app.getNetAddresss("plugin.be-within-call.frontend.work-time.group");
    app._postNetWork({
      url: baseUrl,
      data: {
        aid : this.data.id
      },
      success: ({data : { data,result,msg }}) => {
        if (result !== 1) {
          app.tips(msg)
          return false;
        }
        let newArrDate = [];
        for(let item of data) {
          newArrDate.push(this.timestampToTime(item.date));
        }
        this.setData({
          calendarEvents: newArrDate
        })
      }
    });
  },
  submit() {
    let time = new Date(`${this.data.time_day.split('-')[0]}/${this.data.time_day.split('-')[1]}/${this.data.time_day.split('-')[2]} ${this.data.time_op}`);
    let form = {
      content: this.data.content,
      longitude: this.data.myLocation ? this.data.myLocation.point.lng : "",
      latitude: this.data.myLocation ? this.data.myLocation.point.lat : "",
      province: this.data.location_detail.province,
      city: this.data.location_detail.city,
      district: this.data.location_detail.district,
      street: this.data.location_detail.street,
      address: this.data.location_detail.address,
      start_at: time.getTime() / 1000,
      finish_at: time.getTime() / 1000,
      realname: this.data.location_detail.username,
      mobile: this.data.location_detail.mobile,
      ability_id : this.data.id
    }
    let baseUrl = app.getNetAddresss("plugin.be-within-call.frontend.create-need.appointment");
    app._postNetWork({
      url: baseUrl,
      data: form,
      success: ({data : { data,result,msg }}) => {
        if (result !== 1) {
          app.tips(msg)
          return false;
        }
        wx.navigateTo({
          url: '/packageD/buy/orderPay/orderPay?order_id=' + data.order_ids + '&status=2'
        });
      }
    });
  },
  //将时间戳转换成正常时间格式
  timestampToTime(timestamp) {
    if (!Number(timestamp) || timestamp == "") {
      return "";
    }
    let date = new Date(timestamp * 1000); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
    let Y = date.getFullYear() + "-";
    let M = (date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1) + "-";
    let D = (date.getDate() < 10 ? "0" + date.getDate() : date.getDate());
    return Y + M + D;
  },
  // 将十位数0变为空
  filterDate(value) {
    let newNum = value.split('');
    let text = ''
    if(newNum.indexOf('0') == -1) {
      text = value
    }else {
      text = newNum[1]
    }
    return text
  }
})